'use strict'

const { Controller } = require('egg')

class HomeController extends Controller {
  // 获取数据流列表
  async index() {
    const { ctx, service } = this
    await ctx.isLogin()
    ctx.body = await service.stream.list()
  }

  async stash() {
    const { ctx, service } = this
    const struct = ctx.request.body
    const server = await ctx.model.Server.findOne({ _id: struct.client_id, token: struct.token })
    console.log(server)
    if (!server) {
      ctx.throw(404, '', '认证错误')
    }
    ctx.body = await ctx.model.Stream.create({
      name: `${server.host} 数据流`,
      struct,
      server: server._id,
      remark: 'WebHook',
      user: server.user,
    })
  }

  // 创建数据流
  async create() {
    const { ctx, service } = this
    await ctx.isLogin()
    ctx.body = await service.stream.create()
  }

  // 更新数据流
  async update() {
    const { ctx, service } = this
    await ctx.validateId()
    const stream = await service.stream.update()
    if (!stream) {
      ctx.throw(404, 'not found', '数据流不存在')
    }
    ctx.body = stream
  }

  // 删除数据流
  async destroy() {
    const { ctx, service } = this
    await ctx.isLogin()
    await ctx.validateId()
    const stream = await ctx.model.Stream.findById(ctx.params.id)
    if (!stream) {
      ctx.throw(404, 'not found', '对象不存在')
    }
    if (stream.user.toString() !== ctx.user._id.toString() && !ctx.user.isAdmin) {
      ctx.throw(403, 'not permission', '无权删除')
    }
    ctx.body = await stream.remove()
  }
}

module.exports = HomeController
